<?php

define( 'API_ROOT', dirname( __FILE__ ) . '/' );

/**
 * 通用的主站通信接口
 * 
 */
function api_post($module, $action, $arg = array()) {
	$s = $sep = '';
	foreach ( $arg as $k => $v ) {
		$k = urlencode( $k );
		if (is_array( $v )) {
			$s2 = $sep2 = '';
			foreach ( $v as $k2 => $v2 ) {
				$k2 = urlencode( $k2 );
				$s2 .= "$sep2{$k}[$k2]=" . urlencode( api_stripslashes( $v2 ) );
				$sep2 = '&';
			}
			$s .= $sep . $s2;
		} else {
			$s .= "$sep$k=" . urlencode( api_stripslashes( $v ) );
		}
		$sep = '&';
	}
	$postdata = api_requestdata( $module, $action, $s );
	return api_fopen2( HP_SERVER_URL . '/index.php', 500000, $postdata, '', TRUE, HP_SERVER_IP, 20 );
}
function api_addslashes($string, $force = 0, $strip = FALSE) {
	! defined( 'MAGIC_QUOTES_GPC' ) && define( 'MAGIC_QUOTES_GPC', get_magic_quotes_gpc() );
	if (! MAGIC_QUOTES_GPC || $force) {
		if (is_array( $string )) {
			foreach ( $string as $key => $val ) {
				$string[$key] = api_addslashes( $val, $force, $strip );
			}
		} else {
			$string = addslashes( $strip ? stripslashes( $string ) : $string );
		}
	}
	return $string;
}
function api_stripslashes($string) {
	! defined( 'MAGIC_QUOTES_GPC' ) && define( 'MAGIC_QUOTES_GPC', get_magic_quotes_gpc() );
	if (is_array( $string )) {
		foreach ( $string as $k => $v ) {
			$string[$k] = api_stripslashes( $v );
		}
		return $string;
	} else if (MAGIC_QUOTES_GPC) {
		return stripslashes( $string );
	} else {
		return $string;
	}
}
function api_requestdata($module, $action, $arg = '', $extra = '') {
	$input = api_input( $arg );
	$post = "m=$module&a=$action&inajax=2&input=$input&siteid=" . HP_SITEID . $extra;
	return $post;
}
function api_url($module, $action, $arg = '', $extra = '') {
	$url = HP_SERVER_URL . '/index.php?' . api_requestdata( $module, $action, $arg, $extra );
	return $url;
}
function api_input($data) {
	$s = urlencode( api_authcode( $data . '&agent=' . md5( $_SERVER['HTTP_USER_AGENT'] ) . "&time=" . time(), 'ENCODE', HP_KEY ) );
	return $s;
}
function api_serialize($arr, $htmlon = 0) {
	include_once API_ROOT . '/../uc_client/lib/xml.class.php';
	return xml_serialize( $arr, $htmlon );
}
function api_unserialize($s) {
	include_once API_ROOT . '/../uc_client/lib/xml.class.php';
	return xml_unserialize( $s );
}
function api_authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key = md5( $key ? $key : HP_KEY );
	$keya = md5( substr( $key, 0, 16 ) );
	$keyb = md5( substr( $key, 16, 16 ) );
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr( $string, 0, $ckey_length ) : substr( md5( microtime() ), - $ckey_length )) : '';
	$cryptkey = $keya . md5( $keya . $keyc );
	$key_length = strlen( $cryptkey );
	$string = $operation == 'DECODE' ? base64_decode( substr( $string, $ckey_length ) ) : sprintf( '%010d', $expiry ? $expiry + time() : 0 ) . substr( md5( $string . $keyb ), 0, 16 ) . $string;
	$string_length = strlen( $string );
	$result = '';
	$box = range( 0, 255 );
	$rndkey = array();
	for($i = 0; $i <= 255; $i ++) {
		$rndkey[$i] = ord( $cryptkey[$i % $key_length] );
	}
	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr( ord( $string[$i] ) ^ ($box[($box[$a] + $box[$j]) % 256]) );
	}
	if ($operation == 'DECODE') {
		if ((substr( $result, 0, 10 ) == 0 || substr( $result, 0, 10 ) - time() > 0) && substr( $result, 10, 16 ) == substr( md5( substr( $result, 26 ) . $keyb ), 0, 16 )) {
			return substr( $result, 26 );
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace( '=', '', base64_encode( $result ) );
	}
}
function api_fopen2($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
	$__times__ = isset( $_GET['__times__'] ) ? intval( $_GET['__times__'] ) + 1 : 1;
	if ($__times__ > 2) {
		return '';
	}
	$url .= (strpos( $url, '?' ) === FALSE ? '?' : '&') . "__times__=$__times__";
	return api_fopen( $url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block );
}
function api_fopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
	$return = '';
	$matches = parse_url( $url );
	! isset( $matches['host'] ) && $matches['host'] = '';
	! isset( $matches['path'] ) && $matches['path'] = '';
	! isset( $matches['query'] ) && $matches['query'] = '';
	! isset( $matches['port'] ) && $matches['port'] = '';
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/';
	$port = ! empty( $matches['port'] ) ? $matches['port'] : 80;
	if ($post) {
		$out = "POST $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Referer: $url\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= 'Content-Length: ' . strlen( $post ) . "\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cache-Control: no-cache\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		$out .= $post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Referer: $url\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
	}
	restore_error_handler();
	$fp = @fsockopen( ($ip ? $ip : $host), $port, $errno, $errstr, $timeout );
	if (function_exists( 'reset_error_handler' )) {
		reset_error_handler();
	}
	if (! $fp) {
		return 'Can not open server!';
	} else {
		stream_set_blocking( $fp, $block );
		stream_set_timeout( $fp, $timeout );
		@fwrite( $fp, $out );
		$status = stream_get_meta_data( $fp );
		if (! $status['timed_out']) {
			while ( ! feof( $fp ) ) {
				if (($header = @fgets( $fp )) && ($header == "\r\n" || $header == "\n")) {
					break;
				}
			}
			$stop = false;
			while ( ! feof( $fp ) && ! $stop ) {
				$data = fread( $fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit) );
				$return .= $data;
				if ($limit) {
					$limit -= strlen( $data );
					$stop = $limit <= 0;
				}
			}
		}
		@fclose( $fp );
		return $return;
	}
}
function api_getdata($m = '', $a = '') {
	$return = call_user_func( 'api_post', $m, $a, array() );
	return api_unserialize( $return );
}

/**
 * 发送数据
 */
function senddata($act = 'add', $table = '', $data, $where = '') {
	//savetofile( $data, API_ROOT . './1.txt' );
	$data = base64_encode( serialize( $data ) );
	$result = api_post( 'index', 'senddata', array(
		
		'act' => $act,
		'table' => $table,
		'data' => $data,
		'where' => $where,
		'site_id' => HP_SITEID 
	) );
	//如果返回值不为1，则要写入更新数据表
	return $result;
}
if (! function_exists( 'savetofile' )) {
	function savetofile($data, $file = '') {
		if(!$file) $file = API_ROOT.'/1.txt';
		if (is_array( $data )) {
			ob_start();
			print_r( $data );
			$contents = ob_get_contents();
			ob_end_clean();
		} else {
			$contents = $data;
		}
		$fp = fopen( $file, 'a+' );
		fwrite( $fp, $contents . "\r\n" );
		fclose( $fp );
	}
}

$cnf = API_ROOT . 'config.inc.php';
if (! file_exists( $cnf )) {
	exit( '配置文件不存在！' );
}
require_once (API_ROOT . 'config.inc.php');

